package com.zt.english.utils

import com.zt.english.bean.SubtitlesBean
import java.io.*
import java.util.regex.Pattern


/**
 * srt文件读取解析类
 * 读取srt字幕文件到内存再包装到集合返回。正则表达式匹配字幕文件里的开始，结束时间
 */
class SrtFileParasUtil {
    companion object{
        /**
         * 一秒=1000毫秒
         */
        private val oneSecond = 1000

        private val oneMinute = 60 * oneSecond

        private val oneHour = 60 * oneMinute

        /**
         * 正则表达式，判断是否是时间的格式
         */
        private val equalStringExpress:String = "\\d\\d:\\d\\d:\\d\\d,\\d\\d\\d --> \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d"

        /**
         * srt文件转化到list
         */
        fun parasSrt2List(ips :InputStream):ArrayList<SubtitlesBean>?{
            var line:String? = null
            var br:BufferedReader? = null
            var isr:InputStreamReader? = null

            val list = ArrayList<SubtitlesBean>()

            try {
                isr = InputStreamReader(ips,"UTF-8")
                //缓冲读取流
                br = BufferedReader(isr)
                while (br.readLine().also({ line = it })!=null) {
                    val sm = SubtitlesBean()
                    // 匹配正则表达式，不符合提前结束当前行；
                    if (Pattern.matches(equalStringExpress, line!!)) {
                        // 填充开始时间数据
                        sm.start =  getTime(line!!.substring(0, 12))
                        // 填充结束时间数据
                        sm.end =  getTime(line!!.substring(17, 29))
                        // 填充中文数据
                        sm.contentCh = br.readLine()
                        // 填充英文数据
                        sm.contentEn = br.readLine()
                        // 当前字幕的节点位置
                        sm.node = list.size
                        list.add(sm)
                    }
                }
                return list
            }catch (ex : FileNotFoundException){
                ex.printStackTrace()
            }catch (ex :UnsupportedEncodingException){
                ex.printStackTrace()
            }finally {
                if(br!=null) br.close()
                if(isr!=null) isr.close()
            }
            return null
        }

        /**
         * 将string时间转化为int时间戳毫秒值
         * 00:00:01,920
         */
        private fun getTime(line :String):Int{
            try {
                return line.substring(0, 2).toInt() * oneHour + line.substring(3, 5).toInt() * oneMinute + line.substring(6, 8).toInt() * oneSecond + line.substring(9, line.length).toInt()
            } catch (e: NumberFormatException) {
                e.printStackTrace()
            }
            return 0
        }
    }
}